<?php
// +-------------------------------------------------------------------------------
// | DingZone [ A Rapid Development Framework For Dingtalk ]
// +-------------------------------------------------------------------------------
// | 站点管理员 v1.0
// |
// | Copyright (c) 2014-2018 http://www.heimalanshi.com All rights reserved.
// | Author : Jie
// | Date : 2018-08-09
// +-------------------------------------------------------------------------------

namespace app\core\model;

use think\Model;

class SiteAdmin extends Model {
    /**
     * 根据用户名密码获取用户
     *
     * @param $username
     * @param $password
     * @return null|static
     * @throws \think\exception\DbException
     */
    public static function login($username, $password) {
        $password = SiteAdmin::generatePassword($password);
        $ret = SiteAdmin::get([
            'username' => $username,
            'password' => $password
        ]);
        if (!$ret) {
            return false;
        }
        $user = $ret->getData();
        $user['gmt_last_login'] = time();
        $user['last_login_ip'] = request()->ip();
        SiteAdmin::update([
            'gmt_last_login' => $user['gmt_last_login'],
            'last_login_ip' => $user['last_login_ip']
        ], [
            'id' => $user['id']
        ]);
        return $user;
    }

    /**
     * 检查用户密码
     *
     * @param $id
     * @param $password
     * @return bool
     * @throws \think\exception\DbException
     */
    public static function checkPassword($id, $password) {
        $password = SiteAdmin::generatePassword($password);
        $ret = SiteAdmin::get([
            'id' => $id,
            'password' => $password
        ]);
        if (!$ret) {
            return false;
        }
        return true;
    }

    /**
     * 生成加密过的密码
     *
     * @param $password
     * @return string
     */
    public static function generatePassword($password) {
        $salt = PASSWORD_SALT;
        return md5(md5($password . $salt) . $salt);
    }

    /**
     * 创建用户
     *
     * @param $username
     * @param $password
     * @return $this
     */
    public static function add($username, $password) {
        $password = SiteAdmin::generatePassword($password);
        return SiteAdmin::create([
            'username' => $username,
            'password' => $password
        ]);
    }
}